﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace Lost{
	/// <summary>
	/// 虫洞
	/// 逻辑：物品A进入触发器时，生成克隆体B，B的位置和朝向都要相应地改变
	/// 当A离开触发器的方向与进入触发器的方向的角度>90°的时候，A取代B 
	/// </summary>
	public class Wormhole : MonoBehaviour {
		public static int count = 0;
		class ColonInf{
			public Transform regionTran;
			public Transform colonTran;
			public Vector3 EnterDir;
			public ColonInf(Transform r, Transform c, Vector3 eDir){
				regionTran = r;
				colonTran = c;
				EnterDir = eDir;
			}
			~ColonInf(){
				Debug.Log("~ColonInf");
			}
		}
		[SerializeField] Transform targetTran;
		List<ColonInf> colons = new List<ColonInf>();

		int GetIndex(Transform region){
			int count = 0;
			foreach (ColonInf ci in colons) {
				if (ci.regionTran == region) {
					return count;
				}
				count++;
			}
			return -1;
		}
		void OnTriggerEnter(Collider col){
			if (count++ > 100) {
				return;
			}
			GameObject colon = GameObject.Instantiate (col.gameObject, col.transform.position, col.transform.rotation) as GameObject;
			ColonInf ci = new ColonInf (col.transform, colon.transform, col.transform.position - transform.position);
			colons.Add (ci);
			SetColonTran (ci);
		}
		void Update(){
			foreach (ColonInf ci in colons) {
				SetColonTran (ci);
				if (ci.regionTran.tag == "Player") {
					Debug.Log ("Do Something like Animator");
				}
			}
		}
		void OnTriggerExit(Collider col){
			int index = GetIndex (col.transform);
			ColonInf ci = colons [index];
			Vector3 exitDir = col.transform.position - transform.position;
			if (Vector3.Angle (exitDir, ci.EnterDir) > 90) {
				ci.regionTran.position = ci.colonTran.position;
				ci.regionTran.rotation = ci.colonTran.rotation;
			}
			Destroy (ci.colonTran.gameObject);
			//System.GC.Collect ();
			colons.RemoveAt (index);
		}

		/// 保证生成物的相对位置
		void SetColonTran(ColonInf ci){
			//计算相对于transform的本地坐标
			Vector3 dir = ci.regionTran.position - transform.position;
			Vector3 localPos = new Vector3 (Vector3.Dot (dir, transform.right), Vector3.Dot (dir, transform.up), Vector3.Dot (dir, transform.forward));
			//
			ci.colonTran.position = targetTran.position + targetTran.right * localPos.x + targetTran.up * localPos.y + targetTran.forward * localPos.z;

			Quaternion diffQua = targetTran.rotation * Quaternion.Euler (-transform.rotation.eulerAngles);
			ci.colonTran.rotation = ci.regionTran.rotation * diffQua;
		}
	}
}
